package com.example.dw.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.dw.dto.*;
import com.example.dw.entity.*;
import com.example.dw.mapper.*;
import com.example.dw.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程服务实现类
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private CourseCommentMapper courseCommentMapper;

    @Autowired
    private UserFavoriteCourseMapper userFavoriteCourseMapper;

    @Autowired
    private CourseTypeMapper courseTypeMapper;

    @Autowired
    private UserStudyPeriodMapper userStudyPeriodMapper;

    @Override
    public Course getCourseById(Integer courseid) {
        if (courseid == null) {
            throw new RuntimeException("课程ID不能为空");
        }
        Course course = courseMapper.getCourseById(courseid);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        return course;
    }

    @Override
    public void addCourseComment(Integer userid, CourseCommentDTO commentDTO) {
        // 检查课程是否存在
        Course course = getCourseById(commentDTO.getCourseid());

        // 创建评论
        CourseComment comment = new CourseComment();
        comment.setUserid(userid);
        comment.setCourseid(commentDTO.getCourseid());
        comment.setScore(commentDTO.getScore());
        comment.setContent(commentDTO.getContent());
        comment.setCreatedAt(LocalDateTime.now());

        courseCommentMapper.insert(comment);

        // 更新课程评分（可选：重新计算平均评分）
        Double avgScore = courseCommentMapper.getAverageScoreByCourseId(commentDTO.getCourseid());
        if (avgScore != null) {
            Course updateCourse = new Course();
            updateCourse.setCourseid(commentDTO.getCourseid());
            updateCourse.setStars(avgScore.intValue());
            courseMapper.updateById(updateCourse);
        }
    }

    @Override
    public List<CourseComment> getCourseComment(Integer courseid) {
        if (courseid == null) {
            throw new RuntimeException("课程ID不能为空");
        }
        return courseCommentMapper.getCourseComments(courseid);
    }

    @Override
    public Map<String, Object> getCourseCommentByPage(CourseCommentDTO commentDTO) {
        Integer page = commentDTO.getPage() != null && commentDTO.getPage() > 0 ? commentDTO.getPage() : 1;
        Integer size = commentDTO.getSize() != null && commentDTO.getSize() > 0 ? commentDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<CourseComment> comments = courseCommentMapper.getCourseCommentsByPage(
                commentDTO.getCourseid(), offset, size);
        Integer total = courseCommentMapper.getCourseCommentCount(commentDTO.getCourseid());

        Map<String, Object> result = new HashMap<>();
        result.put("list", comments);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public void changeFavorite(Integer userid, CourseFavoriteDTO favoriteDTO) {
        // 检查当前收藏状态
        UserFavoriteCourse existingFavorite = userFavoriteCourseMapper.checkFavorite(
                userid, favoriteDTO.getCourseid());

        if (existingFavorite != null) {
            // 更新现有记录的状态
            Integer newStatus = (existingFavorite.getStatus() == 0) ? 1 : 0; // 切换状态
            userFavoriteCourseMapper.updateFavoriteStatus(
                    userid, favoriteDTO.getCourseid(), newStatus);
        } else {
            // 创建新的收藏记录，默认为收藏状态
            userFavoriteCourseMapper.insertFavorite(userid, favoriteDTO.getCourseid(), 0);
        }
    }

    @Override
    public Boolean isFavorite(Integer userid, Integer courseid) {
        UserFavoriteCourse favorite = userFavoriteCourseMapper.checkFavorite(userid, courseid);
        return favorite != null && favorite.getStatus() == 0;
    }

    @Override
    public Map<String, Object> getCourseByType(CourseQueryDTO queryDTO) {
        if (queryDTO.getCourseType() == null) {
            throw new RuntimeException("课程类型ID不能为空");
        }

        Integer page = queryDTO.getPage() != null && queryDTO.getPage() > 0 ? queryDTO.getPage() : 1;
        Integer size = queryDTO.getSize() != null && queryDTO.getSize() > 0 ? queryDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<Course> courses = courseMapper.getCoursesByType(queryDTO.getCourseType(), offset, size);
        Integer total = courseMapper.getCourseCountByType(queryDTO.getCourseType());

        Map<String, Object> result = new HashMap<>();
        result.put("list", courses);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public List<CourseType> getCourseTypes() {
        return courseTypeMapper.getAllCourseTypes();
    }

    @Override
    public Map<String, Object> getCourseTypeByPage(CourseQueryDTO queryDTO) {
        Integer page = queryDTO.getPage() != null && queryDTO.getPage() > 0 ? queryDTO.getPage() : 1;
        Integer size = queryDTO.getSize() != null && queryDTO.getSize() > 0 ? queryDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<CourseType> courseTypes = courseTypeMapper.getCourseTypesByPage(offset, size);
        Integer total = courseTypeMapper.getCourseTypeCount();

        Map<String, Object> result = new HashMap<>();
        result.put("list", courseTypes);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public Map<String, Object> getCourseMOHu(CourseQueryDTO queryDTO) {
        if (StrUtil.isBlank(queryDTO.getKeyword())) {
            throw new RuntimeException("搜索关键字不能为空");
        }

        Integer page = queryDTO.getPage() != null && queryDTO.getPage() > 0 ? queryDTO.getPage() : 1;
        Integer size = queryDTO.getSize() != null && queryDTO.getSize() > 0 ? queryDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<Course> courses = courseMapper.searchCourses(queryDTO.getKeyword(), offset, size);
        Integer total = courseMapper.searchCoursesCount(queryDTO.getKeyword());

        Map<String, Object> result = new HashMap<>();
        result.put("list", courses);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public void updatePeriodState(Integer userid, StudyPeriodDTO studyPeriodDTO) {
        // 检查是否已有学习记录
        UserStudyPeriod existingRecord = userStudyPeriodMapper.getUserStudyPeriod(
                userid, studyPeriodDTO.getPeriodid());

        if (existingRecord != null) {
            // 更新现有记录
            userStudyPeriodMapper.updateStudyState(
                    userid, studyPeriodDTO.getPeriodid(), studyPeriodDTO.getState());
        } else {
            // 创建新的学习记录
            userStudyPeriodMapper.insertStudyRecord(
                    userid, studyPeriodDTO.getPeriodid(), studyPeriodDTO.getState(), 
                    studyPeriodDTO.getPeriodType());
        }
    }

    @Override
    public Map<String, Object> getCourseByTypePage(CourseQueryDTO queryDTO) {
        if (queryDTO.getCourseType() == null) {
            throw new RuntimeException("课程类型ID不能为空");
        }

        Integer page = queryDTO.getPage() != null && queryDTO.getPage() > 0 ? queryDTO.getPage() : 1;
        Integer size = queryDTO.getSize() != null && queryDTO.getSize() > 0 ? queryDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<Course> courses = courseMapper.getCoursesByTypePageWeb(queryDTO.getCourseType(), offset, size);
        Integer total = courseMapper.getCourseCountByType(queryDTO.getCourseType());

        Map<String, Object> result = new HashMap<>();
        result.put("list", courses);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }
} 